package cn.z2huo.demo.hello.core.init;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.Ordered;

/**
 * <p>
 *
 * @author z2huo
 */
public abstract class InitializingTask implements ApplicationListener<ContextRefreshedEvent>, Ordered {

    public static final String INIT_TASK_APPLICATION_CONTEXT_TYPE_TEXT = "${hello.initTask.applicationContextType:org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext}";

    @SuppressWarnings("unchecked")
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        Class<? extends ApplicationContext> contextClass = this.getApplicationContextClass();
        if (contextClass == null) {
            try {
                contextClass = (Class<? extends ApplicationContext>) Class.forName(event.getApplicationContext().getEnvironment().resolvePlaceholders(INIT_TASK_APPLICATION_CONTEXT_TYPE_TEXT));
            } catch (Exception e) {
                contextClass = AnnotationConfigApplicationContext.class;
            }
        }
        if (contextClass.isInstance(event.getApplicationContext())) {
            this.execute(event.getApplicationContext());
        }
    }

    public abstract void execute(ApplicationContext context);

    protected Class<? extends ApplicationContext> getApplicationContextClass() {
        return null;
    }

}
